#include "textbubble.h"

#include <QTextDocument>
#include <QTextBlock>
#include <QTextLayout>
#include <QFont>

TextBubble::TextBubble(ChatRole role, const QString &text, QWidget *parent) : BubbleFrame(role, parent)
{
    m_pTextEdit = new QTextEdit();
    m_pTextEdit->setReadOnly(true);
    m_pTextEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_pTextEdit->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_pTextEdit->installEventFilter(this);
    QFont font("Microsoft YaHei");
    font.setPointSize(12);
    m_pTextEdit->setFont(font);
    setPlainText(text);
    setWidget(m_pTextEdit);
    initStyleSheet();
}

bool TextBubble::eventFilter(QObject *watched, QEvent *event)
{
    if (m_pTextEdit == watched && event->type() == QEvent::Paint)
    {
        adjustTextHeight(); // PaintEvent中设置
    }

    return BubbleFrame::eventFilter(watched, event);
}

// 在拉伸聊天界面时，自动调整消息的长度以及高度
void TextBubble::adjustTextHeight()
{
    // 字体到边框的距离默认为4
    qreal doc_margin = m_pTextEdit->document()->documentMargin();
    QTextDocument* doc = m_pTextEdit->document();
    qreal text_height = 0;
    // 将已经显示的文本的每一段的高度相加，即可得到当前显示的文本高度
    for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next()) {
        QTextLayout* pLayout = it.layout();
        QRectF text_rect = pLayout->boundingRect();
        text_height += text_rect.height();
    }

    int vMargin = this->layout()->contentsMargins().top();
    // 设置气泡的高度  文本的高度 + 文本框 + TextEdit边框到气泡边框的距离
    setFixedHeight(text_height + doc_margin * 2 + vMargin * 2);
}

void TextBubble::setPlainText(const QString &text)
{
    m_pTextEdit->setPlainText(text);
    // 找到段落中最大宽度
    qreal doc_margin = m_pTextEdit->document()->documentMargin();
    int margin_left = this->layout()->contentsMargins().left();
    int margin_right = this->layout()->contentsMargins().right();
    QFontMetricsF fm(m_pTextEdit->font());
    QTextDocument* doc = m_pTextEdit->document();
    int max_width = 0;
    // 遍历每一段，找到最宽的那一段
    for (QTextBlock it = doc->begin(); it != doc->end(); it = it.next()) {
        int txtw = int(fm.width(it.text()));
        // 更新最大宽度
        max_width = max_width > txtw ? max_width : txtw;
    }

    // 设置整个气泡的最大宽度
    setMaximumWidth(max_width + doc_margin * 2 + margin_left + margin_right);
}

void TextBubble::initStyleSheet()
{
    m_pTextEdit->setStyleSheet("QTextEdit{background:transparent;border:none}");
}
